package com.flying.refdata.batchload.wind.marketdata;

import com.flying.refdata.model.equity.MarketData;
import com.flying.refdata.service.MarketDataService;
import com.flying.utils.excel.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.Map;

public abstract class AbstractMarketDataUpdater {
    private static final String INDICATOR_MA = "MA";
    private static final String INDICATOR_CLOSE = "CLOSE";
    private static final String INDICATOR_PB = "PB";

    private static final int BATCH_SIZE = 30;

    abstract String getIndicator(Sheet sheet, Cell cell);

    abstract int getMACycles(Sheet sheet, Cell cell);

    void updateMarketData(MarketData data, Sheet sheet, Cell cell) {
        String indicator = getIndicator(sheet, cell);
        switch (StringUtils.trim(indicator).toUpperCase()) {
            case INDICATOR_MA:
                int cycles = getMACycles(sheet, cell);
                switch (cycles) {
                    case 5:
                        data.setMa5(ExcelUtil.asDouble(cell));
                        break;
                    case 10:
                        data.setMa10(ExcelUtil.asDouble(cell));
                        break;
                    case 30:
                        data.setMa30(ExcelUtil.asDouble(cell));
                        break;
                    case 120:
                        data.setMa120(ExcelUtil.asDouble(cell));
                        break;
                    case 250:
                        data.setMa250(ExcelUtil.asDouble(cell));
                        break;
                    default:
                        throw new RuntimeException("Unsupported MA cycles" + cycles);
                }
                break;
            case INDICATOR_CLOSE:
                data.setClosingPrice(ExcelUtil.asDouble(cell));
                break;
            case INDICATOR_PB:
                data.setPb(ExcelUtil.asDouble(cell));
                break;
            default:
                throw new RuntimeException("Unsupported indicator" + indicator);
        }
    }

    static void flushMarketData(MarketDataService service, Map<String, MarketData> datas, boolean forced) {
        if (datas.size() >= BATCH_SIZE || forced) {
            service.saveMarketData(datas.values());
            datas.clear();
        }
    }
}